package io.kimmking.rpcfx.netty;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;

/**
 * Create by chenhd on 2021/10/7.
 */
public class ClientHandler extends SimpleChannelInboundHandler<Object> {


    private ChannelHandlerContext ctx;
    private ChannelPromise promise;
    private String response;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        this.ctx = ctx;
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg != null) {
            FullHttpResponse fullHttpResponse = (FullHttpResponse) msg;
            response = fullHttpResponse.content().toString(CharsetUtil.UTF_8);
            promise.setSuccess();
        } else {
            ctx.fireChannelRead(msg);
        }
    }

    public synchronized ChannelPromise sendMessage(String url, Object message) throws InterruptedException, MalformedURLException {
        while (ctx == null) {
            try {
                TimeUnit.MILLISECONDS.sleep(1);
            } catch (InterruptedException e) {
                //log
            }
        }
        promise = ctx.newPromise();
        ByteBuf byteBuffer = Unpooled.wrappedBuffer(JSON.toJSONString(message).getBytes());
        DefaultFullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
                HttpMethod.POST, url, byteBuffer);
        URL urlObj = new URL(url);
        String host = urlObj.getHost();
        httpRequest.headers().set(HttpHeaders.Names.HOST, host);
        httpRequest.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json");
        httpRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, byteBuffer.readableBytes());
        ctx.writeAndFlush(httpRequest).sync();
        return promise;
    }

    public String getResponse() {
        return response;
    }

}
